package com.taijihuabao.common.commonutils;

import cn.hutool.core.util.IdUtil;
import com.alibaba.druid.util.StringUtils;
import com.taijihuabao.common.exception.ServiceException;
import com.taijihuabao.common.jsonresult.ApplicationResponseCode;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author changhui.tu
 * 文件上传工具类
 */
public class FileInOutPutStreamUtil {

    /**
     * 定义访问路径
     */
    private static final String DIR_PATH_URL_PREFIX = "/profile/";
    /**
     * 文件路径
     */
    private static String filePathForData;

    /**
     * 文件上传
     *
     * @param file
     * @param filePath
     */
    public static void uploadFile(MultipartFile file, String filePath) {
        //生成文件路径
        getUploadPath(filePath);
        //拿到上传文件的后缀
        String fileSuffix = getFileSuffix(file);
        //生成随机文件名
        String fileName = IdUtil.fastSimpleUUID();
        // 拼接后缀
        if (fileSuffix != null) {
            fileName += fileSuffix;
        }
        //创建新文件
        String newFileName = filePath + File.separator + fileName;
        File newFile = new File(newFileName);
        try (FileOutputStream fileOutputStream = new FileOutputStream(newFile)) {
            IOUtils.copy(file.getInputStream(), fileOutputStream);
            filePathForData = DIR_PATH_URL_PREFIX + fileName;
        } catch (IOException e) {
            throw new ServiceException(ApplicationResponseCode.FILE_UPLOAD_ERROR);
        }
    }

    /**
     * 生成文件路径
     *
     * @param folderPath
     */
    private static void getUploadPath(String folderPath) {
        //创建文件
        File file = new File(folderPath);
        //获取抽象父路径名
        File fileParent = file.getParentFile();
        if (!fileParent.exists()) {
            fileParent.mkdirs();
        }
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    /**
     * 获取文件后缀
     *
     * @param file
     * @return
     */
    private static String getFileSuffix(MultipartFile file) {
        if (file == null) {
            return null;
        }
        String fileName = file.getOriginalFilename();
        if (!StringUtils.isEmpty(fileName)) {
            int suffixIndex = file.getOriginalFilename().lastIndexOf(".");
            //判断有无后缀
            if (suffixIndex == -1) {
                return null;
            } else {
                return fileName.substring(suffixIndex);
            }
        }
        return null;
    }

    /**
     * 获取文件路径保存数据库
     *
     * @return
     */
    public static String getFilePathForData() {
        return filePathForData;
    }

}
